package com.wjerp.tplus.server.domain.service.impl;

import com.wjerp.tplus.server.api.request.FieldValueRequest;
import com.wjerp.tplus.server.api.request.QueryCompanyListRequest;
import com.wjerp.tplus.server.api.request.UpdateCompanyInfoRequest;
import com.wjerp.tplus.server.api.response.CompanyInfoResponse;
import com.wjerp.tplus.server.api.response.PageDataResponse;
import com.wjerp.tplus.server.application.CommonService;
import com.wjerp.tplus.server.common.constant.SystemInfoField;
import com.wjerp.tplus.server.common.exception.ServiceException;
import com.wjerp.tplus.server.common.utils.CodeGeneratorUtils;
import com.wjerp.tplus.server.common.utils.SpringContextUtil;
import com.wjerp.tplus.server.domain.entity.CompanyAccountInfo;
import com.wjerp.tplus.server.domain.entity.CompanyInfo;
import com.wjerp.tplus.server.domain.entity.SystemInfo;
import com.wjerp.tplus.server.domain.entity.sys.UserInfo;
import com.wjerp.tplus.server.domain.mapper.CompanyAccountInfoMapper;
import com.wjerp.tplus.server.domain.mapper.CompanyInfoMapper;
import com.wjerp.tplus.server.domain.mapper.SystemInfoMapper;
import com.wjerp.tplus.server.domain.service.CompanyService;
import com.wjerp.tplus.server.domain.service.SystemInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lishuailei
 */
@Service
public class CompanyServiceImpl implements CompanyService, CommonService {

    @Resource
    private CompanyInfoMapper companyInfoMapper;

    @Resource
    private CodeGeneratorUtils codeGeneratorUtils;

    @Resource
    private CompanyAccountInfoMapper companyAccountInfoMapper;

    @Resource
    private SystemInfoMapper systemInfoMapper;


    @Override
    public void addOrUpdateCompanyInfo(String userDisplayId, UpdateCompanyInfoRequest request) throws ServiceException {
        CompanyInfo companyInfo =  new CompanyInfo();
        //生成企业编码
        BeanUtils.copyProperties(request,companyInfo);
        //companyInfo.setCompanyCode(codeGeneratorUtils.generateCompanyCode());
        companyInfo.setCreatedTime(new Date());
        companyInfo.setCreatedUser(userDisplayId);
        companyInfo.setUpdatedTime(new Date());
        companyInfo.setUpdatedUser(userDisplayId);
        if (companyInfo.getId() == null) {
            companyInfoMapper.insertSelective(companyInfo);
            //初始化企业相关配置信息
            initCompanyConfig(companyInfo);
        } else {
            companyInfoMapper.updateByPrimaryKeySelective(companyInfo);
        }
    }

    /**
     * 初始化企业的基础配置信息
     * @param companyInfo
     */
    private void initCompanyConfig(CompanyInfo companyInfo) {
        //1. 公司账户配置信息 company_account_info
        CompanyAccountInfo companyAccountInfo = new CompanyAccountInfo();
        companyAccountInfo.setCompanyCode(companyInfo.getCompanyCode());
        companyAccountInfo.setAccountCode(codeGeneratorUtils.generateCompanyAccountCode());
        companyAccountInfo.setCheckNum(0);
        companyAccountInfo.setOcrNum(0);
        companyAccountInfo.setCreatedTime(new Date());
        companyAccountInfo.setUpdatedTime(new Date());
        companyAccountInfo.setCreatedUser(companyInfo.getCreatedUser());
        companyAccountInfo.setUpdatedUser(companyInfo.getUpdatedUser());
        companyAccountInfoMapper.insertSelective(companyAccountInfo);
        //2. 公司系统配置信息 system_info
        SystemInfoService systemInfoService = SpringContextUtil.getBeanByClass(SystemInfoService.class);
        FieldValueRequest fieldValueRequest = new FieldValueRequest();
        fieldValueRequest.setCheckCompanyName(false);
        fieldValueRequest.setCheckInvoice(false);
        systemInfoService.updateSystemConfig(fieldValueRequest,companyInfo.getCompanyCode(),companyInfo.getUpdatedUser());
    }

    @Override
    public CompanyInfoResponse loadCompanyInfoByCompanyCode(String companyCode) {
        CompanyInfo companyInfo = companyInfoMapper.selectByCompanyCode(companyCode);
        CompanyInfoResponse companyInfoResponse = new CompanyInfoResponse();
        BeanUtils.copyProperties(companyInfo,companyInfoResponse);
        Map<String, List<UserInfo>> userInfoMap = loadUserInfoMap(Arrays.asList(companyInfo.getCreatedUser(),companyInfo.getUpdatedUser()));
        companyInfoResponse.setCreatedUsername(userInfoMap.get(companyInfo.getCreatedUser()).get(0).getName());
        companyInfoResponse.setUpdatedUsername(userInfoMap.get(companyInfo.getUpdatedUser()).get(0).getName());

        return companyInfoResponse;
    }

    @Override
    public PageDataResponse loadCompanyList(QueryCompanyListRequest request) {
        //1.获取符合条件的公司信息数
        Integer totalCount = companyInfoMapper.loadCompanyListCount(request);

        if(totalCount.equals(0)){
            return new PageDataResponse(totalCount, Collections.emptyList());
        }
        //2.获取符合条件的公司信息列表
        List<CompanyInfo> companyInfos = companyInfoMapper.loadCompanyList(request);
        List<String> operatorUserIdList = companyInfos.stream().map(CompanyInfo::getCreatedUser).distinct().collect(Collectors.toList());
        operatorUserIdList.addAll(companyInfos.stream().map(CompanyInfo::getUpdatedUser).distinct().collect(Collectors.toList()));
        Map<String, List<UserInfo>> userInfoMap = loadUserInfoMap(operatorUserIdList);

        List<CompanyInfoResponse> companyInfoResponses = new ArrayList<>();
        companyInfos.forEach(data->{
            CompanyInfoResponse companyInfoResponse = new CompanyInfoResponse();
            BeanUtils.copyProperties(data,companyInfoResponse);

            companyInfoResponse.setCreatedUsername(userInfoMap.get(data.getCreatedUser()).get(0).getName());
            companyInfoResponse.setUpdatedUsername(userInfoMap.get(data.getUpdatedUser()).get(0).getName());
            companyInfoResponses.add(companyInfoResponse);
        });
        return  new PageDataResponse<>(totalCount,companyInfoResponses);
    }

    @Override
    public CompanyInfo loadCompanyInfoByUserCode(String userCode) {
        return  companyInfoMapper.loadCompanyInfoByUserCode(userCode);
    }

    @Override
    public CompanyInfo loadCompanyInfoByAuthCode(String authCode) {
        return companyInfoMapper.selectByAuthCode(authCode);
    }

    @Override
    public List<CompanyInfo> loadCompanyInfoByCompanyCodeList(List<String> companyCodeList) {
        if(CollectionUtils.isEmpty(companyCodeList)){
            return Collections.emptyList();
        }
        return companyInfoMapper.selectByCompanyCodeList(companyCodeList);

    }

    @Override
    public void insertCompanyInfo(CompanyInfo companyInfo) {
        companyInfoMapper.insertSelective(companyInfo);
    }
}
